package com.best.main;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author Jiang Akang
 * employeeId: BG435424
 * @date 2021/6/5
 **/
public class SpringTransactionExample {

    private static String url = "jdbc:mysql://localhost:3306/spring_transaction?useSSL=false&characterEncoding=utf-8&autoReconnect=true";
    private static String user = "root";
    private static String password = "root";

    public static void main(String[] args) {
        // 获取数据源
        final DataSource ds = new DriverManagerDataSource(url, user, password);
        // 编程式事务
        final TransactionTemplate template = new TransactionTemplate();
        // 设置事务管理器
        template.setTransactionManager(new DataSourceTransactionManager(ds));

        template.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {
                Connection conn = DataSourceUtils.getConnection(ds);
                Object savePoint = null;
                try {
                    {
                        // 插入
                        PreparedStatement prepare = conn.prepareStatement("insert into person(id, name) values (?, ?)");
                        prepare.setString(1, "1");
                        prepare.setString(2, "1111");
                        prepare.executeUpdate();
                    }

                    // 设置保存点，回滚的化，不会回滚保存点之前的操作
                    savePoint = transactionStatus.createSavepoint();
                    {
                        // 插入
                        PreparedStatement prepare = conn.prepareStatement("insert into person(id, name) values (?, ?)");
                        prepare.setString(1, "2");
                        prepare.setString(2, "222");
                        prepare.executeUpdate();
                    }

                    {
                        // 更新
                        PreparedStatement prepare = conn.prepareStatement("update person set name = ? where id = ?");
                        prepare.setString(1, "jak");
                        prepare.setInt(2, 6);
                        prepare.executeUpdate();

                        // 模拟异常
//                        int i = 1 / 0;
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    System.out.println("更新失败");
                    if (savePoint != null) {
                        // 回滚到保存点
                        transactionStatus.rollbackToSavepoint(savePoint);
                    } else {
                        transactionStatus.setRollbackOnly();
                    }
                }
                return null;
            }
        });
    }
}
